This problem is mostly related to an optimization.
Suppose I have a very big text (const text = "...") and an big array of keywords (const keywords = ["one", "good days", "ar.i.t", ...]). You can notice that this keywords might be a single word, multiple words or any RegEx expresion. I need to count how many times each keyword (expression) occurs in the text.
My approach would be as follows:
const text = "..."
const keywords = [...]
keywords.forEach(keyword => {
const re = new RegExp(keyword, "gi");
const count = (text.match(re) || []).length;
})
The problem with this approach is that it is very slow (if text is big enough and array as well). I have to iterate through the entire text again and again until every keyword is checked. Could someone suggest an idea of an algorithm that would go through text only once and count occurence for every keyword, or any idea that could solve the problem faster.
This might help slightly:
const str = 'this is a piece of text this is text this is text';
const countOcc = () => {
const regex = /this/g, result, indices = [];
while ((result = regex.exec(str))) {
indices.push(result.index);
}
return indices.length
}